<template>
  <div class="messages-view">
    <NavBar />
    
    <!-- 全局加载状态 -->
    <div v-if="isPageLoading" class="global-loading-container">
      <div class="global-loading">
        <div class="loading-spinner"></div>
        <p>加载消息中心...</p>
      </div>
    </div>
    
    <main class="container" v-else>
      <h1>消息中心</h1>
      
      <div class="messages-container">
        <div class="message-list">
          <div 
            v-for="chat in chats" 
            :key="chat.id"
            class="chat-item"
            :class="{ active: selectedChat && selectedChat.id === chat.id }"
            @click="selectChat(chat)"
          >
            <div class="chat-info">
              <div class="chat-header">
                <h4>{{ chat.name }}</h4>
                <span class="chat-time">{{ formatTime(chat.lastMessageTime) }}</span>
              </div>
              <div class="chat-book">{{ chat.bookTitle }}</div>
              <p class="chat-preview">{{ chat.lastMessage }}</p>
              <span class="unread-badge" v-if="chat.unreadCount > 0">{{ chat.unreadCount }}</span>
            </div>
          </div>
          
          <div class="empty-chats" v-if="chats.length === 0">
            <p>暂无消息</p>
            <router-link to="/" class="btn-browse">浏览书籍</router-link>
          </div>
        </div>
        
        <div class="chat-detail" v-if="selectedChat">
          <div class="chat-header">
            <div class="chat-info">
              <h3>{{ selectedChat.name }}</h3>
              <p class="chat-book">关于: {{ selectedChat.bookTitle }}</p>
            </div>
            <div class="chat-actions">
              <button class="btn-view-book" @click="viewBook(selectedChat.bookId)">查看书籍</button>
            </div>
          </div>
          
          <div class="messages-content">
            <div class="messages-history" ref="messagesHistory">
              <div v-if="isLoadingMessages" class="loading-messages">
                <p>加载消息中...</p>
              </div>
              
              <div v-else-if="selectedChat.messages.length === 0" class="no-messages">
                <p>暂无消息，发送第一条消息开始对话吧！</p>
              </div>
              
              <template v-else>
                <!-- 按日期分组显示消息 -->
                <template v-for="(group, groupIndex) in groupedMessages" :key="groupIndex">
                  <!-- 日期标签 -->
                  <div class="message-date">
                    {{ formatDate(group.date) }}
                  </div>
                  
                  <!-- 该日期下的所有消息 -->
                  <div 
                    v-for="(message, index) in group.messages" 
                    :key="`${groupIndex}-${index}`"
                    class="message"
                    :class="{ 'message-sent': message.isSent, 'message-received': !message.isSent }"
                  >
                    <div class="message-content">
                      <p>{{ message.text }}</p>
                      <span class="message-time">{{ formatDetailTime(message.time) }}</span>
                    </div>
                  </div>
                </template>
              </template>
            </div>
          </div>
          
          <div class="message-input">
            <textarea 
              v-model="newMessage" 
              placeholder="输入消息..."
              @keydown.enter.prevent="sendMessage"
            ></textarea>
            <button 
              class="btn-send" 
              :disabled="!newMessage.trim()"
              @click="sendMessage"
            >
              发送
            </button>
          </div>
        </div>
        
        <div class="no-chat-selected" v-else>
          <div class="placeholder-content">
            <div class="placeholder-icon">💬</div>
            <h3>选择一个聊天</h3>
            <p>从左侧列表选择一个聊天，或者开始新的对话</p>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import NavBar from '../components/NavBar.vue'
import api from '@/api/apiClient'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const chats = ref([])
const selectedChat = ref(null)
const newMessage = ref('')
const messagesHistory = ref(null)
const ws = ref(null)
const wsConnected = ref(false)
const wsReconnecting = ref(false)
const reconnectInterval = ref(3000) // 重连间隔(ms)
const reconnectAttempts = ref(0)
const maxReconnectAttempts = 10
const heartbeatInterval = ref(null)
const currentUserId = localStorage.getItem('userId')
const isLoadingMessages = ref(false)
const isPageLoading = ref(true) // 新增全局页面加载状态

// 发送保持连接的心跳包
const sendHeartbeat = () => {
  if (wsConnected.value && ws.value && ws.value.readyState === WebSocket.OPEN) {
    console.log('发送心跳包...')
    try {
      ws.value.send(JSON.stringify({ type: 'heartbeat' }))
    } catch (e) {
      console.error('发送心跳包失败:', e)
      wsConnected.value = false
      reconnectWebSocket()
    }
  }
}

// 启动定期心跳
const startHeartbeat = () => {
  stopHeartbeat()
  heartbeatInterval.value = setInterval(sendHeartbeat, 30000) // 每30秒
  console.log('心跳检测已启动')
}

// 停止心跳
const stopHeartbeat = () => {
  if (heartbeatInterval.value) {
    clearInterval(heartbeatInterval.value)
    heartbeatInterval.value = null
    console.log('心跳检测已停止')
  }
}

// WebSocket连接
const connectWebSocket = () => {
  return new Promise((resolve, reject) => {
    if (!currentUserId) {
      ElMessage.error('请先登录')
      router.push('/login')
      reject(new Error('未登录'))
      return
    }

    // 已经有连接
    if (wsConnected.value && ws.value && ws.value.readyState === WebSocket.OPEN) {
      console.log('WebSocket已连接，无需重新连接')
      resolve()
      return
    }

    wsReconnecting.value = true
    const wsUrl = `ws://localhost:8080/ws/chat?userId=${currentUserId}`
    console.log('正在连接WebSocket:', wsUrl)
    
    // 关闭现有连接
    if (ws.value && ws.value.readyState !== WebSocket.CLOSED) {
      console.log('关闭现有WebSocket连接')
      ws.value.close()
    }
    
    try {
      ws.value = new WebSocket(wsUrl)
    } catch (e) {
      console.error('创建WebSocket实例失败:', e)
      wsReconnecting.value = false
      reject(e)
      return
    }

    ws.value.onopen = () => {
      console.log('WebSocket连接已建立')
      wsConnected.value = true
      wsReconnecting.value = false
      reconnectAttempts.value = 0
      
      // 启动心跳检测
      startHeartbeat()
      
      // 如果从书籍详情页跳转过来，自动选择对应的聊天
      if (route.query.bookId && route.query.sellerId) {
        console.log('从书籍详情页跳转，自动选择聊天:', route.query)
        selectOrCreateChat(route.query.bookId, route.query.sellerId, route.query.bookTitle, route.query.sellerName)
      }
      resolve()
    }

    ws.value.onmessage = (event) => {
      console.log('收到WebSocket消息:', event.data)
      try {
        const message = JSON.parse(event.data)
        if (message.type === 'heartbeat_ack') {
          console.log('收到心跳响应')
          return
        }
        handleWebSocketMessage(message)
      } catch (error) {
        console.error('解析WebSocket消息失败:', error, event.data)
      }
    }

    ws.value.onerror = (error) => {
      console.error('WebSocket错误:', error)
      wsConnected.value = false
      if (!wsReconnecting.value) {
        ElMessage.error('连接发生错误，将自动重试')
        reconnectWebSocket()
      }
      reject(error)
    }

    ws.value.onclose = (event) => {
      console.log('WebSocket连接已关闭:', event.code, event.reason)
      wsConnected.value = false
      stopHeartbeat()
      
      // 如果不是正常关闭且不在重连中，尝试重连
      if (event.code !== 1000 && !wsReconnecting.value) {
        console.log('WebSocket非正常关闭，尝试重连')
        reconnectWebSocket()
      }
    }
    
    // 添加连接超时处理
    setTimeout(() => {
      if (!wsConnected.value && ws.value && ws.value.readyState === WebSocket.CONNECTING) {
        console.log('WebSocket连接超时')
        ws.value.close()
        wsReconnecting.value = false
        reject(new Error('连接超时'))
      }
    }, 10000)
  })
}

// 重连WebSocket
const reconnectWebSocket = () => {
  if (wsReconnecting.value || reconnectAttempts.value >= maxReconnectAttempts) {
    return
  }
  
  wsReconnecting.value = true
  reconnectAttempts.value++
  
  console.log(`第${reconnectAttempts.value}次尝试重连，${reconnectInterval.value / 1000}秒后重试...`)
  
  setTimeout(() => {
    console.log('正在重连...')
    connectWebSocket()
      .then(() => {
        console.log('重连成功')
        wsReconnecting.value = false
      })
      .catch(error => {
        console.error('重连失败:', error)
        wsReconnecting.value = false
        
        // 增加重连间隔时间，最大30秒
        reconnectInterval.value = Math.min(reconnectInterval.value * 1.5, 30000)
        
        // 如果还有重试次数，继续重连
        if (reconnectAttempts.value < maxReconnectAttempts) {
          reconnectWebSocket()
        } else {
          ElMessage.error('连接服务器失败，请刷新页面重试')
        }
      })
  }, reconnectInterval.value)
}

// 处理WebSocket消息
const handleWebSocketMessage = (message) => {
  console.log('收到WebSocket消息:', message)
  
  switch (message.type) {
    case 'message':
      console.log('处理新消息:', message)
      handleNewMessage(message)
      break
    case 'system':
      console.log('系统消息:', message.content)
      ElMessage.info(message.content)
      break
    case 'error':
      console.error('错误消息:', message.message)
      ElMessage.error(message.message)
      break
    case 'confirmation':
      console.log('消息确认:', message)
      handleMessageConfirmation(message)
      break
    case 'notification':
      console.log('收到通知:', message.content)
      ElMessage.info(message.content)
      break
    case 'heartbeat':
      console.log('收到心跳响应')
      break
    default:
      console.log('未知类型的消息:', message)
  }
}

// 处理新消息
const handleNewMessage = (message) => {
  console.log('处理新消息数据:', message)
  
  // 确保使用正确的字段名称和类型，处理可能缺失的字段
  const senderId = parseInt(message.sender_id || message.senderId || 0)
  const receiverId = parseInt(message.receiver_id || message.receiverId || currentUserId)
  const bookId = parseInt(message.book_id || message.bookId || 0)
  const timestamp = message.created_at || message.timestamp || new Date().toISOString()
  const content = message.content || ''
  const messageId = message.messageId || message.id || Date.now()
  
  // 验证基本必要字段
  if (!senderId || !content) {
    console.error('消息缺少必要字段:', message)
    return
  }
  
  console.log('处理后的消息参数:', { 
    senderId, 
    receiverId, 
    bookId, 
    messageId,
    currentUserId: parseInt(currentUserId) 
  })
  
  // 首先尝试更简单的匹配 - 仅按发送者/接收者ID找聊天
  let chat = null
  
  // 检查是否已有同一用户的聊天
  for (const c of chats.value) {
    console.log('检查聊天:', {
      chatId: c.id,
      chatSellerId: c.sellerId,
      chatBuyerId: c.buyerId,
      messageSenderId: senderId
    })
    
    // 匹配逻辑1: 按发送者ID匹配
    if (c.sellerId === senderId || c.buyerId === senderId) {
      console.log('找到发送者匹配的聊天')
      chat = c
      
      // 如果有bookId，更新聊天的书籍信息
      if (bookId && bookId !== 0) {
        c.bookId = bookId
        
        // 如果消息中有书籍标题，更新聊天的书籍标题
        if (message.bookTitle) {
          c.bookTitle = message.bookTitle
        }
      }
      
      break
    }
  }
  
  // 现在只有在找不到任何匹配的发送者/接收者时，才尝试用bookId匹配
  if (!chat && bookId && bookId !== 0) {
    for (const c of chats.value) {
      if (c.bookId === bookId) {
        if ((c.sellerId === senderId || c.sellerId === receiverId) && 
            (c.buyerId === senderId || c.buyerId === receiverId)) {
          console.log('找到书籍ID和用户ID匹配的聊天')
          chat = c
          break
        }
      }
    }
  }
  
  // 如果找不到匹配的聊天，创建一个新的聊天
  if (!chat) {
    console.log('未找到匹配的聊天，创建新聊天:', { senderId, receiverId, bookId })
    
    // 通过发送者ID确定是否为卖家
    const chatId = Date.now()
    const isSellerMessage = senderId !== parseInt(currentUserId)
    
    chat = {
      id: chatId,
      bookId: bookId || 0,
      bookTitle: message.bookTitle || '未知书籍',
      sellerId: isSellerMessage ? senderId : parseInt(currentUserId),
      buyerId: isSellerMessage ? parseInt(currentUserId) : senderId,
      name: isSellerMessage ? '卖家' : '买家',
      lastMessage: '',
      lastMessageTime: new Date(),
      unreadCount: 0,
      messages: []
    }
    
    console.log('创建的新聊天:', chat)
    
    // 如果消息中没有书籍标题但有bookId，尝试获取
    if (!message.bookTitle && bookId) {
      api.book.getDetail(bookId)
        .then(response => {
          if (response && response.title) {
            chat.bookTitle = response.title
            // 强制更新组件
            chats.value = [...chats.value]
          }
        })
        .catch(error => console.error('获取书籍信息失败:', error))
    }
    
    // 添加到聊天列表
    chats.value.push(chat)
  } else {
    console.log('找到匹配的聊天:', chat)
  }
  
  // 添加消息到聊天
  const newMessage = {
    id: messageId,
    text: content,
    time: new Date(timestamp),
    isSent: senderId === parseInt(currentUserId)
  }
  
  console.log('添加新消息到聊天:', newMessage)
  
  chat.messages.push(newMessage)
  chat.lastMessage = content
  chat.lastMessageTime = new Date(timestamp)
  
  // 如果不是当前选中的聊天，增加未读数
  if (!selectedChat.value || selectedChat.value.id !== chat.id) {
    chat.unreadCount = (chat.unreadCount || 0) + 1
  }
  
  // 如果是当前选中的聊天，滚动到底部
  if (selectedChat.value && selectedChat.value.id === chat.id) {
    scrollToBottom()
  }
  
  // 强制更新组件
  chats.value = [...chats.value]
  
  console.log('消息处理完成，当前聊天列表:', chats.value)
}

// 处理消息确认
const handleMessageConfirmation = (confirmation) => {
  console.log('消息已送达:', confirmation)
  
  // 如果消息包含ID，可以标记为已读
  if (confirmation.messageId) {
    api.messages.markAsRead(confirmation.messageId)
      .then(() => console.log('消息已标记为已读'))
      .catch(error => console.error('标记消息已读失败:', error))
  }
}

// 选择或创建聊天
const selectOrCreateChat = async (bookId, sellerId, bookTitle, sellerName) => {
  try {
    // 只根据sellerId查找聊天，不考虑bookId
    let chat = chats.value.find(c => c.sellerId === parseInt(sellerId))
    
    if (!chat) {
      // 如果不存在，创建新聊天
      chat = {
        id: Date.now(), // 临时ID
        bookId: parseInt(bookId),
        bookTitle: bookTitle,
        sellerId: parseInt(sellerId),
        buyerId: parseInt(currentUserId),
        name: sellerName || '卖家',
        lastMessage: '',
        lastMessageTime: new Date(),
        unreadCount: 0,
        messages: []
      }
      chats.value.push(chat)
    } else {
      // 如果已存在聊天，更新书籍信息
      chat.bookId = parseInt(bookId)
      chat.bookTitle = bookTitle
      // 如果有卖家名称且当前没有，则更新
      if (sellerName && chat.name === '卖家') {
        chat.name = sellerName
      }
    }
    
    // 选择聊天
    selectChat(chat)
    
    // 获取历史消息
    await fetchChatHistory(chat)
  } catch (error) {
    console.error('选择或创建聊天失败:', error)
    ElMessage.error('加载聊天失败')
  }
}

// 获取聊天历史
const fetchChatHistory = async (chat) => {
  try {
    // 设置加载状态
    isLoadingMessages.value = true
    
    console.log('获取聊天历史，参数:', {
      userId1: parseInt(currentUserId),
      userId2: chat.sellerId
    })
    
    const response = await api.messages.getHistory(parseInt(currentUserId), chat.sellerId)
    
    console.log('聊天历史原始响应:', response)
    
    // 检查响应格式，处理不同类型的返回值
    let messageList = []
    
    // 情况1: 直接返回数组
    if (Array.isArray(response)) {
      messageList = response
      console.log('聊天历史API直接返回数组格式:', messageList.length, '条消息')
    } 
    // 情况2: 标准响应格式 {code, message, data}
    else if (response && response.code === 200) {
      if (Array.isArray(response.data)) {
        messageList = response.data
        console.log('聊天历史API返回标准格式，data是数组:', messageList.length, '条消息')
      } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
        messageList = response.data.list
        console.log('聊天历史API返回标准格式，data.list是数组:', messageList.length, '条消息')
      } else if (response.data && response.data.messages && Array.isArray(response.data.messages)) {
        messageList = response.data.messages
        console.log('聊天历史API返回标准格式，data.messages是数组:', messageList.length, '条消息')
      }
    }
    
    if (messageList.length > 0) {
      // 打印第一条消息的完整格式，帮助调试
      console.log('消息格式示例:', messageList[0])
      
      // 使用新数组替换，确保Vue检测到更新
      chat.messages = messageList.map(msg => ({
        text: msg.content || msg.text || '',
        time: new Date(msg.created_at || msg.createTime || msg.timestamp || Date.now()),
        isSent: (msg.sender_id === parseInt(currentUserId)) || (msg.senderId === parseInt(currentUserId))
      }))
      
      // 按时间排序消息
      chat.messages.sort((a, b) => a.time - b.time)
      
      // 更新最后一条消息
      const lastMsg = chat.messages[chat.messages.length - 1]
      if (lastMsg) {
        chat.lastMessage = lastMsg.text
        chat.lastMessageTime = lastMsg.time
      }
      
      console.log(`加载了 ${chat.messages.length} 条消息历史`)
    } else {
      console.log('没有历史消息')
      chat.messages = []
    }
    
    // 滚动到底部
    scrollToBottom()
  } catch (error) {
    console.error('获取聊天历史失败:', error)
    ElMessage.error('获取聊天历史失败')
  } finally {
    // 无论成功失败都关闭加载状态
    isLoadingMessages.value = false
  }
}

// 发送消息
const sendMessage = () => {
  if (!newMessage.value.trim() || !selectedChat.value) return
  
  // 检查WebSocket连接状态
  if (!wsConnected.value || !ws.value || ws.value.readyState !== WebSocket.OPEN) {
    console.log('WebSocket未连接，尝试重连...')
    ElMessage.warning('连接中断，正在尝试重连...')
    connectWebSocket()
      .then(() => {
        console.log('重连成功，重新发送消息')
        sendMessage() // 重连成功后重试发送
      })
      .catch(error => {
        console.error('重连失败，无法发送消息:', error)
        ElMessage.error('连接失败，请刷新页面后重试')
      })
    return
  }
  
  const messageText = newMessage.value.trim()
  
  const message = {
    receiver_id: selectedChat.value.sellerId,
    book_id: selectedChat.value.bookId,
    content: messageText
  }
  
  console.log('正在通过WebSocket发送消息:', message)
  
  // 通过WebSocket发送消息
  try {
    ws.value.send(JSON.stringify(message))
    
    // 立即更新本地UI显示
    const newLocalMessage = {
      text: messageText,
      time: new Date(),
      isSent: true
    }
    
    // 添加消息到本地
    selectedChat.value.messages.push(newLocalMessage)
    selectedChat.value.lastMessage = messageText
    selectedChat.value.lastMessageTime = new Date()
    
    // 强制Vue重新渲染
    selectedChat.value = {...selectedChat.value}
    chats.value = [...chats.value]
    
    // 清空输入框
    newMessage.value = ''
    
    // 滚动到最新消息
    setTimeout(scrollToBottom, 50) // 延迟滚动以确保DOM更新
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('消息发送失败，请稍后重试')
  }
}

onMounted(() => {
  console.log('组件挂载，初始化数据')
  isPageLoading.value = true // 设置全局加载状态
  
  // 先直接获取聊天列表并打印详细信息
  console.log('直接获取聊天列表查看结果...')
  api.messages.getChats()
    .then(response => {
      console.log('直接获取的聊天列表原始响应:', response)
      
      // 处理不同的响应格式
      let chatList = []
      
      // 情况1: 直接返回数组
      if (Array.isArray(response)) {
        chatList = response
        console.log('API直接返回数组格式的聊天列表:', chatList.length)
      } 
      // 情况2: 标准响应格式 {code, message, data}
      else if (response && response.code === 200 && response.data) {
        if (Array.isArray(response.data)) {
          chatList = response.data
          console.log('API返回标准格式，data是数组:', chatList.length)
        } else if (response.data.list && Array.isArray(response.data.list)) {
          chatList = response.data.list
          console.log('API返回标准格式，data.list是数组:', chatList.length)
        }
      }
      
      // 打印聊天列表详情
      if (chatList.length > 0) {
        console.log('聊天列表数量:', chatList.length)
        
        // 打印每个聊天的关键信息
        chatList.forEach((chat, index) => {
          console.log(`聊天${index+1}:`, {
            id: chat.id || chat.partnerId,
            name: chat.sellerName || chat.partnerName || '卖家', 
            bookId: chat.bookId,
            bookTitle: chat.bookTitle,
            lastMessage: chat.lastMessage,
            unreadCount: chat.unreadCount
          })
        })
      } else {
        console.log('聊天列表为空')
      }
    })
    .catch(error => {
      console.error('直接获取聊天列表失败:', error)
    })
  
  // 然后再初始化WebSocket和获取完整数据
  connectWebSocket()
    .then(() => {
      console.log('WebSocket已连接，获取聊天列表')
      fetchChats()
    })
    .catch(error => {
      console.error('WebSocket连接失败', error)
      // 即使WebSocket失败也尝试获取聊天列表
      fetchChats()
    })
    
  // 添加页面可见性监听，处理后台切换
  document.addEventListener('visibilitychange', handleVisibilityChange)
})

onUnmounted(() => {
  console.log('组件卸载，清理资源')
  stopHeartbeat()
  if (ws.value) {
    try {
      ws.value.close(1000, 'Component unmounted')
    } catch (e) {
      console.error('关闭WebSocket失败:', e)
    }
    ws.value = null
  }
})

const fetchChats = async () => {
  try {
    isPageLoading.value = true // 设置全局加载状态为true
    console.log('获取聊天列表...')
    
    const response = await api.messages.getChats()
    console.log('聊天列表响应:', response)
    
    // 根据响应格式处理数据
    let chatList = []
    
    // 情况1: 直接返回数组
    if (Array.isArray(response)) {
      chatList = response
      console.log('API直接返回数组格式的聊天列表:', chatList)
    } 
    // 情况2: 标准响应格式 {code, message, data}
    else if (response && response.code === 200 && response.data) {
      if (Array.isArray(response.data)) {
        chatList = response.data
        console.log('API返回标准格式，data是数组:', chatList)
      } else if (response.data.list && Array.isArray(response.data.list)) {
        chatList = response.data.list
        console.log('API返回标准格式，data.list是数组:', chatList)
      }
    }
    
    // 处理聊天数据
    if (chatList.length > 0) {
      chats.value = chatList.map(chat => ({
        id: chat.id || chat.partnerId || Date.now(), // 确保有ID
        name: chat.sellerName || chat.partnerName || '卖家',
        bookId: chat.bookId || 0,
        bookTitle: chat.bookTitle || '未知书籍',
        sellerId: chat.sellerId || chat.partnerId || 0,
        buyerId: chat.buyerId || currentUserId,
        lastMessage: chat.lastMessage || '',
        lastMessageTime: new Date(chat.lastMessageTime || Date.now()),
        unreadCount: chat.unreadCount || 0,
        messages: []
      }))
      
      console.log('处理后的聊天列表:', chats.value)
      
      // 从URL参数中获取预选的聊天
      if (route.query.bookId && route.query.sellerId) {
        console.log('检查URL参数中的聊天:', route.query)
        // WebSocket连接建立后会处理自动选择
        await selectOrCreateChat(route.query.bookId, route.query.sellerId, route.query.bookTitle, route.query.sellerName)
      } else if (chats.value.length > 0) {
        // 否则选择第一个聊天
        console.log('选择第一个聊天')
        await selectChat(chats.value[0])
      }
    } else {
      console.log('聊天列表为空')
    }
  } catch (error) {
    console.error('获取聊天列表失败:', error)
    ElMessage.error('获取聊天列表失败')
  } finally {
    // 无论成功或失败，都结束加载状态
    isPageLoading.value = false
  }
}

const selectChat = async (chat) => {
  console.log('选择聊天:', chat)
  selectedChat.value = chat
  
  // 如果有未读消息，则标记为已读
  if (chat.unreadCount > 0) {
    // 获取聊天伙伴ID (sellerId 或 partnerId)
    const partnerId = chat.sellerId || chat.partnerId
    
    try {
      console.log('标记聊天为已读，伙伴ID:', partnerId)
      // 调用接口标记聊天为已读
      const response = await api.messages.markChatAsRead(partnerId)
      console.log('标记聊天为已读结果:', response)
      
      // 更新本地未读计数
      chat.unreadCount = 0
    } catch (error) {
      console.error('标记聊天为已读失败:', error)
    }
  }
  
  // 立即获取消息历史
  await fetchChatHistory(chat)
}

// 滚动到最新消息
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesHistory.value) {
      try {
        console.log('滚动到底部', messagesHistory.value.scrollHeight)
        messagesHistory.value.scrollTop = messagesHistory.value.scrollHeight
      } catch (e) {
        console.error('滚动失败', e)
      }
    }
  })
}

const viewBook = (bookId) => {
  router.push(`/book/${bookId}`)
}

const formatTime = (date) => {
  const now = new Date()
  const diffDays = Math.floor((now - date) / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    // 今天
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else if (diffDays === 1) {
    // 昨天
    return '昨天'
  } else if (diffDays < 7) {
    // 一周内
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    return days[date.getDay()]
  } else {
    // 更早
    return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
  }
}

const formatDetailTime = (date) => {
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

const formatDate = (date) => {
  const now = new Date()
  const diffDays = Math.floor((now - date) / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else {
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
  }
}

// 将消息按日期分组
const groupedMessages = computed(() => {
  if (!selectedChat.value || !selectedChat.value.messages || selectedChat.value.messages.length === 0) {
    return [];
  }
  
  // 按日期分组
  const groups = [];
  let currentDate = null;
  let currentGroup = null;
  
  // 首先按时间排序
  const sortedMessages = [...selectedChat.value.messages].sort((a, b) => a.time - b.time);
  
  sortedMessages.forEach(message => {
    // 提取日期部分 (年月日)
    const messageDate = new Date(message.time);
    messageDate.setHours(0, 0, 0, 0); // 重置时分秒，只保留日期
    
    // 如果是新的一天或第一条消息
    if (!currentDate || messageDate.getTime() !== currentDate.getTime()) {
      currentDate = messageDate;
      currentGroup = {
        date: messageDate,
        messages: []
      };
      groups.push(currentGroup);
    }
    
    // 将消息添加到当前日期组
    currentGroup.messages.push(message);
  });
  
  return groups;
});

// 处理页面可见性变化
const handleVisibilityChange = () => {
  if (document.visibilityState === 'visible') {
    console.log('页面重新可见，检查WebSocket连接')
    
    // 页面重新可见时先直接获取聊天列表
    console.log('页面重新可见，直接获取聊天列表...')
    api.messages.getChats()
      .then(response => {
        console.log('页面重新可见后直接获取的聊天列表:', response)
        
        // 处理不同的响应格式
        let chatList = []
        
        // 情况1: 直接返回数组
        if (Array.isArray(response)) {
          chatList = response
          console.log('API直接返回数组，聊天数量:', chatList.length)
        } 
        // 情况2: 标准响应格式 {code, message, data}
        else if (response && response.code === 200 && response.data) {
          if (Array.isArray(response.data)) {
            chatList = response.data
            console.log('标准格式数据，聊天数量:', chatList.length)
          } else if (response.data.list && Array.isArray(response.data.list)) {
            chatList = response.data.list
            console.log('标准格式嵌套数据，聊天数量:', chatList.length)
          }
        }
        
        if (chatList.length === 0) {
          console.log('聊天列表为空')
        }
      })
      .catch(error => {
        console.error('页面重新可见后获取聊天列表失败:', error)
      })
    
    // 检查并重连WebSocket
    if (!wsConnected.value || !ws.value || ws.value.readyState !== WebSocket.OPEN) {
      console.log('WebSocket连接已断开，尝试重连')
      connectWebSocket()
        .then(() => console.log('重连成功'))
        .catch(error => console.error('重连失败:', error))
    }
  }
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  font-size: 1.8rem;
  color: #1f2937;
  margin-bottom: 2rem;
}

.messages-container {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 1.5rem;
  height: 70vh;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.message-list {
  border-right: 1px solid #e5e7eb;
  overflow-y: auto;
  height: 100%;
}

.chat-item {
  display: flex;
  padding: 1rem;
  border-bottom: 1px solid #e5e7eb;
  cursor: pointer;
  transition: background-color 0.2s;
}

.chat-item:hover {
  background-color: #f9fafb;
}

.chat-item.active {
  background-color: #eff6ff;
}

.chat-info {
  flex: 1;
  min-width: 0;
  position: relative;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.25rem;
}

.chat-header h4 {
  margin: 0;
  font-size: 1rem;
  color: #1f2937;
}

.chat-time {
  font-size: 0.75rem;
  color: #6b7280;
}

.chat-book {
  font-size: 0.8rem;
  color: #6b7280;
  margin-bottom: 0.25rem;
}

.chat-preview {
  font-size: 0.9rem;
  color: #6b7280;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.unread-badge {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #ef4444;
  color: white;
  font-size: 0.75rem;
  min-width: 18px;
  height: 18px;
  border-radius: 9px;
  padding: 0 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #6b7280;
  font-style: italic;
  background-color: #f9fafb;
  border-radius: 8px;
  margin: 1rem 0;
}

.empty-chats {
  text-align: center;
  padding: 2rem;
  color: #6b7280;
}

.btn-browse {
  display: inline-block;
  margin-top: 1rem;
  padding: 0.5rem 1rem;
  background-color: #3b82f6;
  color: white;
  border-radius: 4px;
  font-size: 0.9rem;
  text-decoration: none;
}

.chat-detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.chat-detail .chat-header {
  padding: 1rem;
  border-bottom: 1px solid #e5e7eb;
  background-color: #f9fafb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 60px;
  flex-shrink: 0;
}

.chat-detail .chat-info h3 {
  margin: 0 0 0.25rem;
  font-size: 1.1rem;
  color: #1f2937;
}

.chat-detail .chat-info .chat-book {
  margin: 0;
}

.btn-view-book {
  padding: 0.5rem 1rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
}

.messages-content {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.messages-history {
  padding: 1rem;
  background-color: #f9fafb;
  overflow-y: auto;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.message {
  max-width: 70%;
  margin-bottom: 1rem;
  display: flex;
}

.message-sent {
  align-self: flex-end;
}

.message-received {
  align-self: flex-start;
}

.message-content {
  padding: 0.75rem 1rem;
  border-radius: 1rem;
  position: relative;
}

.message-sent .message-content {
  background-color: #3b82f6;
  color: white;
  border-bottom-right-radius: 0.25rem;
}

.message-received .message-content {
  background-color: white;
  color: #1f2937;
  border-bottom-left-radius: 0.25rem;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.message-content p {
  margin: 0 0 0.5rem;
}

.message-time {
  font-size: 0.75rem;
  opacity: 0.8;
  display: block;
  text-align: right;
}

.message-date {
  text-align: center;
  margin: 1rem 0;
  color: #6b7280;
  font-size: 0.85rem;
  background-color: rgba(249, 250, 251, 0.8);
  padding: 0.25rem 0.5rem;
  border-radius: 1rem;
  display: inline-block;
  align-self: center;
  width: auto;
}

.message-input {
  padding: 1rem;
  border-top: 1px solid #e5e7eb;
  display: flex;
  gap: 0.5rem;
  background-color: white;
  flex-shrink: 0;
  min-height: 70px;
}

.message-input textarea {
  flex: 1;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  resize: none;
  height: 2.5rem;
  min-height: 2.5rem;
  max-height: 8rem;
  font-family: inherit;
  font-size: 0.95rem;
}

.message-input textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.btn-send {
  padding: 0 1.5rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-send:hover:not(:disabled) {
  background-color: #2563eb;
}

.btn-send:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.no-chat-selected {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f9fafb;
}

.placeholder-content {
  text-align: center;
  padding: 2rem;
}

.placeholder-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.placeholder-content h3 {
  margin: 0 0 0.5rem;
  color: #1f2937;
}

.placeholder-content p {
  color: #6b7280;
  margin: 0;
}

.loading-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #6b7280;
  background-color: #f9fafb;
  border-radius: 8px;
  margin: 1rem 0;
}

.loading-messages p {
  display: flex;
  align-items: center;
}

.loading-messages p:after {
  content: "";
  width: 1rem;
  height: 1rem;
  margin-left: 0.5rem;
  border: 2px solid #e5e7eb;
  border-radius: 50%;
  border-top-color: #3b82f6;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .messages-container {
    grid-template-columns: 1fr;
  }
  
  .message-list {
    display: none;
  }
  
  .message-list.active {
    display: block;
  }
  
  .chat-detail, .no-chat-selected {
    display: none;
  }
  
  .chat-detail.active {
    display: flex;
  }
}

/* 添加全局加载样式 */
.global-loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 70vh;
  width: 100%;
}

.global-loading {
  text-align: center;
  padding: 2rem;
  background-color: #f9fafb;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.loading-spinner {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 3px solid rgba(59, 130, 246, 0.2);
  border-radius: 50%;
  border-top-color: #3b82f6;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style> 